package br.com.vpsa.previdordevendas.controller.filtro;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.vpsa.previdordevendas.controller.CallbackController;
import br.com.vpsa.previdordevendas.model.pojo.UsuarioSessao;
import br.com.vpsa.previdordevendas.model.util.AuthenticationUtil;

public class AutenticacaoFilter implements Filter{

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException 
	{
		if( servletRequest instanceof HttpServletRequest )
		{
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			
			if( CallbackController.SERVLET_PATH.equals(request.getServletPath()) )
			{
				String codeParam = request.getParameter(CallbackController.CODE_PARAM);
				
				if( codeParam != null && ! codeParam.isEmpty() ){
					filterChain.doFilter(servletRequest, servletResponse);
					return;					
				}
				
				String errorParam = request.getParameter(CallbackController.ERROR_PARAM);
				
				if( errorParam != null && ! errorParam.isEmpty() ){
					redirect( AuthenticationUtil.STORE_URI, servletResponse );
					return;
				}
			}
			
			HttpSession session = request.getSession();
			
			if( session != null )
			{
				Object usuarioSessionObj = session.getAttribute(UsuarioSessao.USUARIO_SESSION_KEY);
				
				if( usuarioSessionObj instanceof UsuarioSessao )
				{
					UsuarioSessao usuarioSessao = (UsuarioSessao) usuarioSessionObj;
					
					if( usuarioSessao.isAtivo() ){
						filterChain.doFilter(servletRequest, servletResponse);
						return;
					}
				}
			}
		}
		
		redirect(AuthenticationUtil.getUrlLoginVpsa(),servletResponse);
	}

	private void redirect(String url, ServletResponse servletResponse) throws IOException {
		if( servletResponse instanceof HttpServletResponse ){
			HttpServletResponse response = (HttpServletResponse) servletResponse;
			response.sendRedirect(url);
		}
	}
	
	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
